<?php
class AdminManager
{
  private $_db;

  public function __construct($db)
  {
    $this->setDb($db);
  }

  public function add(Admin $admin)
  {
    $q = $this->_db->prepare('INSERT INTO admin SET nom = :nom, prenom = :prenom, idRefCollege = :idRefCollege, password = :password');

    $q->bindValue(':nom', $admin->nom());
    $q->bindValue(':prenom', $admin->prenom());
    $q->bindValue(':idRefCollege', $admin->idRefCollege());
    $q->bindValue(':password', $admin->password());

    $q->execute();
  }

  public function delete(Admin $admin)
  {
    $this->_db->exec('DELETE FROM admin WHERE id = '.$admin->id());
  }

  public function get($id)
  {
    $id = (int) $id;

    $q = $this->_db->query('SELECT * FROM admin WHERE id = '.$id);
    $donnees = $q->fetch();
    return new Admin($donnees);
  }

  public function getList()
  {
    $admins = array();

    $q = $this->_db->query('SELECT * FROM admin ORDER BY id');

    while ($donnees = $q->fetch())
    {
      $admins[] = new Admin($donnees);
    }

    return $admins;
  }

  public function update(Admin $admin)
  {
    $q = $this->_db->prepare('UPDATE admin SET nom = :nom, prenom = :prenom, idRefCollege = :idRefCollege WHERE id = :id');

	$q->bindValue(':nom', $admin->nom());
    $q->bindValue(':prenom', $admin->prenom());
    $q->bindValue(':idRefCollege', $admin->idRefCollege());
    $q->bindValue(':id', $admin->id(), PDO::PARAM_INT);
	
    $q->execute();
  }

  public function setDb(PDO $db)
  {
    $this->_db = $db;
  }
  
  public function connexion($login, $mdp) //Etablie une session de connexion
  {
	if($login != '' && $mdp != '')
	{
		$login = explode('.', $login);
		if(sizeof($login) == 2){
			$q = $this->_db->query('SELECT * FROM admin WHERE prenom = \''.$login[0].'\' AND nom = \''.$login[1].'\'');
			$donnees = $q->fetch();
			if(!$donnees){ return array("Status" => "Login introuvable", "Admin" => NULL); } else {
				$p = $this->_db->query('SELECT password FROM admin WHERE id='.$donnees[0]);
				$password = $p->fetch();
				if($password[0] == hash('sha256', $mdp)){
					$_SESSION["Admin"] = $this->get($donnees[0]);
					return array("Status" => "Connexion reussite", "Admin" => $_SESSION["Admin"]);	
				} else { return array("Status" => "Mot de passe incorrect", "Admin" => NULL); }
			}
		} else {
			return array("Status" => "Login incorrect", "Admin" => NULL);
		}	
	} else {
		return array("Status" => "Champ incomplet", "Admin" => NULL);
	}
  }
  
  public function deconnexion() //Détruit la session et déconnecte l’administrateur
  {
	$_SESSION = NULL;
	session_destroy();  
  }
}
?>